#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	
	_airport_site = DM_Chapter_Location;
	_airport_site_pos = _airport_site select XF_MAP_LOCATION_CENTER;
	_airport_site_size = _airport_site select XF_MAP_LOCATION_SIZE;
	
	_vip_found = false;
	_vip_alive = true;
	_vip_updated = false;

	_player_detected = false;

	_enemy_initial_counts = ([_airport_site_pos,350,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
	_unique_id = 0;
	_reinforcements = 10;
	_detected_time = time;

	_reinforcement_trigger = _enemy_initial_counts / 4;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_enemy_initial_counts,_reinforcement_trigger], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_enemy_counts = ([_airport_site_pos,350,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		_vip_found = ["jip_vip_found",false] call XNetGetJIP;
		_vip_alive = ["jip_vip_alive",true] call XNetGetJIP;
		_vip_lead = ["jip_vip_lead",false] call XNetGetJIP;
		
		if (["jip_player_detected",false] call XNetGetJIP) then {_player_detected = true;};
		
		if (_vip_found and !_vip_updated) then {
			DM_VIP = [DM_VIP,group DM_VIP,getPos DM_VIP,"LEAD",["You took the pilot back!","You did your best... the pilot died!","jip_vip_lead","jip_vip_alive",[getPos FLAG_BASE,[200,200],0,false]],"doStop this; removeAllWeapons this;"] call XfMissionCreateMissionUnit;
			_vip_updated = true;
			["ArrestPilot","", "","",[],"Succeeded"] call XfMissionTask;
			"The pilot is under arrest! Now bring him and the helicopter back!" call XfMissionMessageToAll;
		};

		if (!alive DM_Target) then {
			_chapter_succeeded = false;
			DM_Mission_Chapter_CanRun = false;
		};
		
		if (((DM_Target distance FLAG_BASE) < 200) && ((getPos DM_Target) select 2 < 1) && (count (crew DM_Target) == 0)) then {
			"You brought the Helicopter back! Very nice job!" call XfMissionMessageToAll;
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
			sleep 10;
		};

		if (DM_Mission_Chapter_CanRun AND _player_detected and !_detected_updated) then {
			_detected_updated = true;
			"You are detected! Reinforcements will surely be called!" call XfMissionMessageToAll;
			_detected_time = time;
		};
		// diag_log Format["(%1)[%2]: %3: %4: en:%5  kill:%6  det:%7  flee:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Loop",_enemy_counts,_dealer_killed,_player_detected,_dealer_fleeing];
		If (DM_Mission_Chapter_CanRun AND _player_detected AND (_reinforcements > 0) AND !_vip_updated) then {
			// If the player is detected and no reinforcement is on the way.. Then we send new troops in :)
			if ((_enemy_initial_counts - _enemy_counts) > _reinforcement_trigger) then {
				if (_unique_id == 0) then {
					// If the reinforcement function returns a value greater than 0, it means a reinforcement was created!
					_unique_id = [d_enemy_side,[_airport_site_pos,_airport_site_size],"RANDOM",DM_Mission_RandomReinforcement] call XfMissionCallReinforcement;
					if ((_unique_id) > 0) then {
						diag_log Format["(%1)[%2]: %3: %4: reinf:%5, diff:%6, ini:%7, vec:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Sending reinforcement",_reinforcements,_enemy_diff,_enemy_initial_counts];
						_reinforcements = _reinforcements - 1;
						hint "Reinforcement";
					};
				};
			} else {
				_unique_id = 0;
			};
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	
	While {DM_Mission_Mission_CanRun && (([_airport_site_pos,_airport_site_size,d_enemy_side] call XfMissionGetZoneSideCount) select 0) > 3} do {
		sleep 5;
	};
	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_airport_site","_airport_site_pos","_airport_site_size","_troops_power","_troops_coeff","_grpSpecOps","_i"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];
	_site_type = XF_MAP_LOCATION_TYPE_AIRPORT;
	_airport_site = [_site_type] call XfMissionGetRandomSpot;
	// In case there is no airport site defined on this map
	// if ((count _airport_site) <= 0) then {
		// _site_type = XF_MAP_LOCATION_TYPE_MILITARY;
		// _airport_site = [_site_type] call XfMissionGetRandomSpot;
		// diag_log Format["(%1)[%2]: %3; %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Picking Up Alternate Location Type",_site_type];
	// };
	// In case there is no airport or military site defined on this map
	if ((count _airport_site) <= 0) then {
		_site_type = XF_MAP_LOCATION_TYPE_GRASSLAND;
		_airport_site = [_site_type] call XfMissionGetRandomSpot;
		diag_log Format["(%1)[%2]: %3; %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Picking Up Alternate Location Type",_site_type];
	};
	_airport_site_pos = _airport_site select XF_MAP_LOCATION_CENTER;
	if ((count _airport_site) <= 0) exitWith {"Could not pick a random airport" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	while { (count _airport_site > 0) && ((_airport_site_pos distance FLAG_BASE) < 700)} do {
		_airport_site = [_site_type] call XfMissionGetRandomSpot;
		_airport_site_pos = _airport_site select XF_MAP_LOCATION_CENTER;
	};
	if ((count _airport_site) <= 0) exitWith {"Could not pick a random airport" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	
	_airport_site_pos = _airport_site select XF_MAP_LOCATION_CENTER;
	_airport_site_size = _airport_site select XF_MAP_LOCATION_SIZE;
	_airport_site_name = _airport_site select XF_MAP_LOCATION_DISPLAYNAME;
		
	DM_Chapter_Position = _airport_site_pos;
	DM_Chapter_Location = _airport_site;
	
	// This indicates where the mission takes place
	[_airport_site_pos,_airport_site_size,_airport_site_name] call XfMissionCurrentPosition;
	diag_log Format["(%1)[%2]: %3; %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Picked Up Location",DM_Chapter_Location];
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_airport_site_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};
	// The marker which indicates the buildings zone
	[false,["chapter1_airport_site_zone", _airport_site_pos, "ELLIPSE", "ColorRed", [_airport_site_size,_airport_site_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;

	[false,["chapter1_airport_site_position",_airport_site_pos, "ICON", "ColorRed", [1,1],"Helicopter Prototype",0,"hd_objective","",0.6]] call XfMissionMarker;

	// We increase the zone is needed to avoid having all units packed up.
	if (_airport_site_size < 200) then { _airport_site_size = 200; };
	
	["jip_vip_found",false] call XNetSetJIP;
	["jip_vip_alive",false] call XNetSetJIP;
	["jip_vip_lead",false] call XNetSetJIP;
	
	// Position in the base
	_prototype_pos = [];
	_pilot_pos_hiding = [];
	_building_pos = ([_airport_site_pos,_airport_site_size,"HIDE"] call XfMissionBuildingAreaPosASL);
	if ((count _building_pos) > 0) then {
		_pilot_pos_hiding = _building_pos select 0;
	} else {
		_pilot_pos_hiding = [_airport_site_pos, _airport_site_size / 2] call XfGetRanPointCircle;
	};
	diag_log Format["(%1)[%2]: %3; %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Pilot Pos",_pilot_pos_hiding];
	if ((count _pilot_pos_hiding) <= 0) exitWith {"Could not pick a pilot location" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	
	_building = objNull;
	_objects = nearestObjects [_airport_site_pos, ["Land_Hangar_2", "land_ibr_hangar", "Land_SS_hangar"], _airport_site_size];
	if (count _objects > 0) then {
		_building = _objects call XfRandomArrayVal;
	};
	if (isNull _building) then {
		_i_tries2 = 30;
		_zone = _airport_site_size / 2;
		if (_zone < 120) then { _zone = 120; };
		while { ( count _prototype_pos <= 0) && _i_tries2 > 0 } do {
			_prototype_pos = [_airport_site_pos,_zone,"WarfareBDepot"] call  XfMissionRanObjectivePos;
			if (count _prototype_pos > 0) then {
				// The following check makes sure the area is really big enough...
				// diag_log Format["(%1)[%2]: %3; %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Checking Chopper Position",_prototype_pos];
				_prototype_pos = (_prototype_pos isflatempty [
								8,	//--- Minimal distance from another object
								0,				//--- If 0, just check position. If >0, select new one
								0,				//--- Max gradient
								8,	//--- Gradient area
								0,				//--- 0 for restricted water, 2 for required water,
								false,				//--- True if some water can be in 25m radius
								FLAG_BASE		//--- Ignored object
								]);
				if (count _prototype_pos > 0) exitWith {};
			};
			// We move around the position to find another suitable spot.
			_prototype_pos = [];
			_i_tries2 = _i_tries2 - 1;
		};
		if ((count _prototype_pos) <= 0) then {
			_prototype_pos = [_airport_site_pos,_zone,"Mi24_V"] call  XfMissionRanObjectivePos;
		};
	} else {
		switch (typeof _building) do {
			case "Land_Hangar_2": {
				_prototype_pos = _building modelToWorld [0,25,0];		
			};
			case "land_ibr_hangar": {
				_prototype_pos = _building modelToWorld [0,25,0];		
			};
			case "Land_SS_hangar": {
				_prototype_pos = _building modelToWorld [0,-35,0];		
			};
			default {
				_prototype_pos = _building modelToWorld [0,-25,0];
				_empty_pos = _prototype_pos findEmptyPosition [0,30,"Mi24_V"];
				if ((count _empty_pos) > 0) then {
					_prototype_pos = _empty_pos;
				};
			};
		};
	};
	diag_log Format["(%1)[%2]: %3; %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Prototype Pos",_prototype_pos];
	
	if ((count _prototype_pos) <= 0) exitWith {"Could not pick a chopper location" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	
	_grp = [d_enemy_side] call x_creategroup;
	DM_VIP = ["RU_Soldier_Pilot",_grp,_pilot_pos_hiding,"ARREST",["You caught the pilot, congratulations!","Damn, you killed the pilot....","jip_vip_found","jip_vip_alive"],"doStop this;"] call XfMissionCreateMissionUnit;
	DM_VIP setPosASL _pilot_pos_hiding;
	DM_Target = ["Mi24_V",_prototype_pos,"REGISTER",[],"","NONE"] call XfMissionCreateMissionObject;
	DM_Target setDir (random 360);
	DM_Target addEventHandler ["getin",{_vec = (_this select 0); _unit = (_this select 2); if ((side _unit) != d_side_player) then {_unit action ["getout",_vec]; unassignVehicle _unit; _unit leaveVehicle _vec;};}];
	
	// The trigger which will send reinforcement when the player is detected!
	["jip_player_detected",false] call XNetSetJIP;
	[_airport_site_pos,350,d_own_side,d_enemy_side,"jip_player_detected"] call XfMissionSideDetected;

	// This populates the town of Polana
	[d_enemy_side,[_airport_site_pos,_airport_site_size],true] call XfMissionPopulateLocation;
	// This will create snipers automatically if selected in the mission setup
	[d_enemy_side,[_airport_site_pos,_airport_site_size],DM_Mission_Snipers] call XfMissionCreateSnipersArea;

	["StealTheHelicopter","Steal The Helicopter", Format["A new model of Helicopter has arrived at the %1 AirBase.<br />Arrest the pilot of the prototype and bring both the pilot and the aircraft back at the base!<br />Good luck!",_airport_site_name],"",[],"Created"] call XfMissionTask;
	["ArrestPilot","Arrest the Pilot", "We need the pilot of the prototype alive in order to interrogate him.<br />We count on you!","",[],"Created"] call XfMissionTask;
	// This will create air support automatically if selected in the mission setup
	[d_enemy_side,[_airport_site_pos,_airport_site_size],DM_Mission_AirSupport] call XfMissionCallAirSupport;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	"Congratulations! This prototype will be very helpful!" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"You tried but failed... you'll do better next time." call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;